import logging
from odoo.exceptions import UserError

_logger = logging.getLogger(__name__)


class RpBackdoorDeal20230109(object):

    @classmethod
    def csv_import_for_country__data(cls, env, csv_reader, headers):
        """
            从csv文件中导入国家信息
        """
        for csv in csv_reader:
            _country_area_code = csv[0] if csv[0] else False
            _country_name = _country_area_code.strip()[0:-2].strip()
            _country_code = _country_area_code.strip()[-2:].strip()
            if not env['res.country'].search([('code', '=', _country_code)]):
                # 如果国家不存在，创建
                env['res.country'].create({'name': _country_name, 'code': _country_code})

    @classmethod
    def csv_import_for_state__city_county_code(cls, env, csv_reader, headers, dict_data):
        """
        导入省市区以及邮编信息
        """
        # 获取数据
        for csv in csv_reader:
            # 获取数据
            data_list = csv[2].strip().split(' ')
            _country_code = data_list[len(data_list) - 1]
            _country_name = csv[2][:csv[2].find(_country_code)].strip()
            _province_name = csv[int(dict_data['province_name'])] if dict_data['province_name'] != '' and csv[int(dict_data['province_name'])] != '' else False  # 获取省
            _city_name = csv[int(dict_data['city_name'])] if dict_data['city_name'] != '' and csv[int(dict_data['city_name'])] != '' else False  # 获取市
            _county_name = csv[int(dict_data['county_name'])] if dict_data['county_name'] != '' and csv[int(dict_data['county_name'])] != '' and dict_data['county_name'] else False  # 获取区/县
            # 处理国家数据
            related_country_id = env['res.country'].search([('code', '=', _country_code)], limit=1)
            if not related_country_id:
                _logger.warning("国家:" + _country_name + '未找到')
                raise UserError('国家未找到')
            # 处理省级数据
            # 省名称包含小括号的单独处理（如中国）
            index_start = _province_name.find('(')
            index_end = _province_name.find(')')
            if index_start + 1 == index_end or index_end < index_start:
                _logger.warning('省:' + _province_name + '存在问题！')
                raise UserError('省的数据存在问题')
            _province_name = _province_name[index_start + 1:index_end] if index_start != -1 and index_end != -1 and _country_code == 'CN' else _province_name
            related_province_id = env['res.country.state'].search([('name', '=', _province_name), ('country_id', '=', related_country_id.id)])
            if not related_province_id:
                # 创建省级记录
                related_province_id = env['res.country.state'].create({'name': _province_name, 'country_id': related_country_id.id})
            # 处理市级数据
            # 市级数据特殊处理
            index_start = _city_name.find('(')
            index_end = _city_name.find(')')
            if index_start != -1 and index_end != -1 and _country_code == 'CN':
                if index_start + 1 == index_end or index_end < index_start:
                    _logger.warning('市:' + _city_name + '存在问题！')
                    raise UserError('市级的数据存在问题')
                _city_name = "{}({})".format(_city_name[index_start + 1:index_end], _city_name[:index_start].strip())
            related_city_id = env['res.city'].search([('name', '=', _city_name), ('state_id', '=', related_province_id.id), ('country_id', '=', related_country_id.id)])
            if not related_city_id:
                related_city_id = env['res.city'].create({'name': _city_name, 'country_id': related_country_id.id, 'state_id': related_province_id.id})
            # 处理区级数据
            # 区县级数据特殊处理
            index_start = _county_name.find('(') if _county_name else -1
            index_end = _county_name.find(')') if _county_name else -1
            if index_start != -1 and index_end != -1 and _country_code == 'CN':
                if index_start + 1 == index_end or index_end < index_start:
                    _logger.warning('区/县' + _county_name + '存在问题！')
                    raise UserError('区县数据存在问题')
                _county_name = "{}({})".format(_county_name[index_start + 1:index_end], _county_name[:index_start].strip())
            related_county_id = env['res.county'].search([('name', '=', _county_name), ('city_id', '=', related_city_id.id), ('state_id', '=', related_province_id.id), ('country_id', '=', related_country_id.id)])
            if not related_county_id and _county_name:
                related_county_id = env['res.county'].create({'name': _county_name,
                                                              'city_id': related_city_id.id,
                                                              'state_id': related_province_id.id,
                                                              'country_id': related_country_id.id})

            # 处理邮编
            if csv[0].strip().lower() in ['', 'none']:
                _logger.warning(_country_name + '的邮编不存在')
                continue
            # 邮编特殊处理
            index = csv[0].find(',')
            if index != -1:
                # 邮编存在多个
                list_data = csv[0].split(',')
                for data in list_data:
                    cls.create_postcode_logic(csv, env, related_city_id, related_country_id, related_county_id, related_province_id, data.strip())
            else:
                cls.create_postcode_logic(csv, env, related_city_id, related_country_id, related_county_id, related_province_id, csv[0].strip())

    @classmethod
    def create_postcode_logic(cls, csv, env, related_city_id, related_country_id, related_county_id, related_province_id, name):
        related_postal_code = env['rp.postal.code'].search([('name', '=', name), ('city_id', '=', related_city_id.id), ('state_id', '=', related_province_id.id), ('country_id', '=', related_country_id.id)])
        if not related_postal_code:
            values = {
                'name': name,
                'city_id': related_city_id.id,
                'country_id': related_country_id.id,
                'state_id': related_province_id.id
            }
            if related_county_id:
                values['county_ids'] = [(4, related_county_id.id)]
            env['rp.postal.code'].create(values)
        else:
            if related_county_id:
                related_postal_code.update({'county_ids': [(4, related_county_id.id)]})
